#require "ruby-debug"

$version = "0.007.1(D)"

begin
f=File.new("session.txt","r")
ln=f.readline
f.close

if ln=="\fON"
  puts "Legend of Zelda - Startup"
  puts "-------------------------\n"  
  puts "Another instance of this program is currently running.\n"
  puts "Due to resource conflicts, multiple instances of this program cannot run simultaneously."
  puts "\n\nThis instance will now exit."
  puts "\n\n\tPress ENTER to continue."
  STDIN.gets
  exit
end

$sf=File.new("session.txt","r+")
$sf.truncate(0)
$sf.write("\fON")
$sf.flock(File::LOCK_SH | File::LOCK_NB)

trap(0) {    $sf.truncate(0); $sf.flock(File::LOCK_UN)  ;$sf.write("\fOFF"); $sf.close  }

puts "Legend of Zelda - Startup"
puts "-------------------------\n"

$window=""

require "logger.rb"
$flog=Logger.new("logs/log.txt", 'daily')
#$olog=Logger.new(STDOUT)

$flog << "\n\n***SESSION START***\n"
$flog.info("Start") {""}
$flog.datetime_format = "%H:%M:%S "
$flog << "**Environment: Ruby Version=#{VERSION}; Platform=#{RUBY_PLATFORM}; Proc=#{$$}**\n"

#puts "Loading RubyGems..."
#require "rubygems"

puts "Loading Gosu..."
require "gosu"
#puts "Gosu loaded successfully.\n"

ModuleAbbr="Launch"

$flog.info(ModuleAbbr) {"Loading external libraries..."}
puts "Loading external libraries..."
require "inifile.rb"
require "ftools.rb"
 # require "bigdecimal"
 # require "bigdecimal/math"
 # include BigMath
  require "find.rb"
  require "zip.rb"
  #require "bmputils"
  #require "camellia"
  #require "mojo_magick/init"
  require "EasyBMP"
require "pathname"
#require "rjb"

$flog.info(ModuleAbbr) {"Loading game modules..."}
puts "Loading game modules...\n"
require "error.rb"
require "image.rb"
require "mouse.rb"
require "window.rb"
require "static.rb"
require "gui.rb"
#require "java.rb"
#jrequire "javax.imageio.ImageIO"
require "collision.rb"
require "framework.rb"
require "movement.rb"
require "combat.rb"
require "player.rb"
require "ai.rb"
require "dataparse.rb"
require "maprender.rb"
require "saveload.rb"
require "ini.rb"
#require "drb.rb"

#require "customapi.rb"

def loadPrefs(n)  
    
    prefsfile=Ini.new("app.ini")
    
    options = [
      Ini::Option.new("Appearance::Fullscreen", ["True","False",0,1], "True"),
      Ini::Option.new("Debug::Enabled", ["True","False",0,1], "True"),
      Ini::Option.new("Debug::ConsoleEnabled", ["True","False",0,1], "True"),
      Ini::Option.new("Debug::TraceEnabled", ["True","False",0,1], "True"),
      Ini::Option.new("Debug::AutoTrace", ["True","False",0,1], "True"),
      Ini::Option.new("Logger::Mode", ["Off","Disabled","Auto","Custom"], "Auto"),
      Ini::Option.new("Logger::Level", ["Debug","Info","Warning","Warn","Error","Fatal","Auto"], "Auto")
    ]
    
    options.each { |opt| prefsfile.loadOption(opt) }
    
    prefsfile.validate
       
    if prefsfile.optionIsEqual?("Appearance","Fullscreen","True")
      $fullscreen=true
      $flog.info("MODE") {"Mode: Fullscreen"}
      puts "Mode: Fullscreen"
    else
      $fullscreen=false
      $flog.info("MODE") {"Mode: Windowed"}
      puts "Mode: Windowed"
    end
    
    if prefsfile.optionIsEqual?("Debug","Enabled","True")
      $debug=true
      $flog.info("MODE") {"Mode: Debug"}
      puts "Mode: Debug"
      $flog.level = Logger::DEBUG
    else
      $debug=false
      $flog.info("MODE") {"Mode: Release"}
      puts "Mode: Release"
      $flog.level = Logger::INFO
    end
    
    if prefsfile.optionIsEqual?("Logger","Mode","Off") or prefsfile.optionIsEqual?("Logger","Mode","Disabled")
      $flog.warn("Logger") {"Logging off"}
      $flog.level = Logger::FATAL
    elsif prefsfile.optionIsEqual?("Logger","Mode","Custom")
      case prefsfile["Logger"]["Mode"].upcase
        when "DEBUG"
          $flog.info("Logger") {"Treshold: Debug"}
          $flog.level = Logger::DEBUG        
        when "INFO"
          $flog.info("Logger") {"Treshold: Info"}
          $flog.level = Logger::INFO        
        when "WARN"       
          $flog.warn("Logger") {"Treshold: Warning"}
          $flog.level = Logger::WARN    
        when "WARNING"
          $flog.warn("Logger") {"Treshold: Warning"}
          $flog.level = Logger::WARN    
        when "ERROR"
          $flog.warn("Logger") {"Treshold: Error"}
          $flog.level = Logger::ERROR      
        when "FATAL"
          $flog.warn("Logger") {"Treshold: Fatal"}
          $flog.level = Logger::FATAL
      end
    end
    
    if prefsfile.optionIsEqual?("Console","Enabled","True")
      DebugConsole.enabled=true
    end
    if prefsfile.optionIsEqual?("Trace","Enabled","True")
      TracePanel.enabled=true
      if prefsfile.optionIsEqual?("Trace","AutoTrace","True")
          
      end    
    end    
    end

$appdir=File.dirname(File.expand_path($0))

module Kernel

  def Boolean(string)
    return true if string == true || string =~ /^true$/i
    return false if string == false || string.nil? || string =~ /^false$/i
    raise ArgumentError.new("invalid value for Boolean: \"#{string}\"")
  end

end

class SplashScreen < Gosu::Window
  def initialize
    super(640, 480, false, 20)
    self.caption = "The Legend of Zelda"
    @background_image = Gosu::Image.new(self, "img/banners/splash.bmp", true)
    @done=false
  end
  
  def update
    $flog.info(ModuleAbbr) {"Loading configurations..."}
    puts "Loading configurations..."
    
    ini=IniFile.new("app.ini")
    
    #prefs=tame(ini)
    #binary file with two bits. First bit = boolean debug mode? Second bit = boolean fullscreen? 

    loadPrefs(ini)

  #  $flog.info(ModuleAbbr) {"Configurations loaded"}
  #  puts "Configurations loaded\n"
  #  $flog.info(ModuleAbbr) {"Registering window..."}
  #  puts "Registering window..."
    
  #  $flog.info(ModuleAbbr) {"Registered window."}
  #  puts "Registered window."
  #  $flog.info(ModuleAbbr) {"Launching window..."}
  #  puts "Launching window..."
    
  #  $flog.info(ModuleAbbr) {"Extracting data..."}
  #  puts "Extracting data..."
   # $flog.debug(ModuleAbbr) {"Extracting data files..."}
   # $flog.debug(ModuleAbbr) {"Extracting scripts..."}
   # $flog.debug(ModuleAbbr) {"Extracting images..."}
   # #system("7za.exe e img.dat -r[/img]")
   # $flog.debug(ModuleAbbr) {"Extracting audio..."}
   
    RubyScript::Utils.RunEvent("Plugin Init")
    
    @done=true
    if @done
      if not ($debug or ini["Appearance"]["ForceSplash"]=="False")
        puts "\nLaunching in:\n3"
        sleep(1)
        puts "2"
        sleep(1)
        puts "1"
        sleep(1)
        puts "0"
      end
      close
     # $flog.debug(ModuleAbbr) {"Registering main window..."}
     # puts "Registering main window..."
      $window=GameWindow.new($fullscreen)
     # $flog.debug(ModuleAbbr) {"Launching main window..."}
     # puts "Launching main window..."
      $window.show      
    end 
  end

  def draw
    @background_image.draw(0, 0, 0)
  end
end

SplashScreen.new.show

RubyScript::Utils.RunEvent("Shut Down")

$flog.info("Exit") {"Status: OK"}
$flog << "***SESSION END***"
exit

rescue
  if $flog
    $flog.fatal("Fatal Error") {$!}
    $flog.error("Exit Cmd") {"Terminal: Fatal Runtime Error"}
    $flog.error("Exit") {"Status: Fatal Error Encountered"}
  end
  system("cls")
  system("clear")
  puts "A fatal error has occured:\n\n"
  raise
ensure
  #system("7za.exe a img.dat -r[/img]")
  if $sf
    $sf.truncate(0)
    $sf.flock(File::LOCK_UN)  
    $sf.write("\fOFF")
    $sf.close
  end
  require 'fileutils.rb'
  FileUtils.rm_f Dir.glob("temp/*.*")
end